package com.junbao.androidinterview.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.junbao.androidinterview.R;
import com.junbao.androidinterview.dialog.LoadingDialog;
import com.junbao.androidinterview.net.interceptor.LoggerInterceptor;
import com.junbao.androidinterview.utils.LogUtils;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * author : Majunbao
 * github : https://github.com/MaJunBaox
 * time   : 2022/8/7 3:58 下午
 * desc   : Okhttp网络请求
 */
public class OkhttpActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnGetExecute;
    private Button btmGetEnqueue;
    private Button btnPostExecute;
    private Button btnPostEnqueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_okhttp);
        initView();
        initData();
    }

    private void initView() {
        btnGetExecute = (Button) findViewById(R.id.btn_get_execute);
        btmGetEnqueue = (Button) findViewById(R.id.btm_get_enqueue);
        btnPostExecute = (Button) findViewById(R.id.btn_post_execute);
        btnPostEnqueue = (Button) findViewById(R.id.btn_post_enqueue);

        btnGetExecute.setOnClickListener(this);
        btmGetEnqueue.setOnClickListener(this);
        btnPostExecute.setOnClickListener(this);
        btnPostEnqueue.setOnClickListener(this);
    }


    private void initData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_get_execute:
                loadDataSync();
                break;
            case R.id.btm_get_enqueue:
                loadDataAsync();
                break;
            case R.id.btn_post_execute:
                postSync();
                break;
            case R.id.btn_post_enqueue:
                break;
        }
    }

    private void postSync() {
        RequestBody formBody = new FormBody.Builder()
                .add("search", "Uncle")
                .build();

        //新建OkhttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor())
                .build();

        Request request = new Request.Builder()
                .url("https://en.wikipedia.org/w/index.php")
                .post(formBody)
                .build();
        okHttpClient.newCall(request).enqueue(mCallback);

    }

    private Callback mCallback = new Callback(){

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            LogUtils.d("success");
        }

        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            LogUtils.d("failure"+e.getMessage());
        }
    };

    private void loadDataAsync() {
        LoadingDialog dialog = new LoadingDialog.Build(this).build();
        dialog.show();
        String url = "https://publicobject.com/helloworld.txt";
        //构建get请求
        Request req = new Request.Builder()
                .get()
                .url(url)
                .header("token","majunbao")
                .build();
        //新建OkhttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor())
                .build();
        okHttpClient.newCall(req).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                //失败子线程执行
                LogUtils.d(e.getMessage());
                dialog.dismiss();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //成功子线程执行
                String string = response.body().string();
                LogUtils.d(string);
                dialog.dismiss();
            }
        });
    }

    /**
     * 同步get请求
     */
    private void loadDataSync() {
        //开启子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "https://publicobject.com/helloworld.txt";
                //构建get请求
                Request req = new Request.Builder().get().url(url).build();
                //新建OkhttpClient
                OkHttpClient okHttpClient = new OkHttpClient();
                try {
                    Response response = okHttpClient.newCall(req).execute();
                    String string = response.body().string();
                    LogUtils.d(string);
                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtils.d(e.getMessage().toString());
                }
            }
        }).start();
    }


    private void sendJsonPost(){
        String json = "";

        //缓存大小
        int cacheSize = 10*1024*1024; //10m
        File externalCacheDir = getExternalCacheDir();
        Cache cache = new Cache(externalCacheDir,cacheSize);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cache(cache)
                .build();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url("")
                .post(requestBody)
                .build();

    }


    private void yuanma(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .build();
        Call call = okHttpClient.newCall(new Request.Builder().build());


    }
}